package com.studentmanagement.ui;

import com.studentmanagement.model.User;

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {
    private User currentUser;
    private JPanel mainContentPanel;
    private JList<String> menuList;

    public MainFrame(User user) {
        this.currentUser = user;
        initComponents();
        setupLayout();
        loadInitialPanel();
    }

    private void initComponents() {
        setTitle("学生信息管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1100, 700);
        setLocationRelativeTo(null); // 居中显示窗口
        setResizable(false);

        // 主内容面板 (使用CardLayout切换不同视图)
        mainContentPanel = new JPanel(new CardLayout());
        mainContentPanel.setBorder(BorderFactory.createEtchedBorder());


        // 菜单
        String[] menuItems = getMenuItemsForRole(currentUser.getRole());
        menuList = new JList<>(menuItems);
        menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        menuList.setSelectedIndex(0); // 默认选中首页
        menuList.setBackground(new Color(240, 240, 240));
        menuList.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        menuList.setFixedCellHeight(35);
        menuList.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 使用微软雅黑字体
        
        // 添加自定义渲染器，为"退出系统"菜单项设置特殊样式
        menuList.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, 
                    int index, boolean isSelected, boolean cellHasFocus) {
                
                JLabel label = (JLabel) super.getListCellRendererComponent(
                        list, value, index, isSelected, cellHasFocus);
                
                // 设置所有项目的通用样式
                label.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
                
                // 如果是"退出系统"菜单项，设置特殊样式
                if (value.equals("退出系统")) {
                    // 添加上边框，与其他菜单项分隔
                    label.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(210, 210, 210)),
                            BorderFactory.createEmptyBorder(5, 10, 5, 10)
                    ));
                    
                    // 如果没有被选中，使用红色
                    if (!isSelected) {
                        label.setForeground(new Color(231, 76, 60));
                    }
                }
                
                return label;
            }
        });
    }

    private void setupLayout() {
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(menuList), mainContentPanel);
        splitPane.setDividerLocation(200); // 设置左侧菜单宽度
        splitPane.setEnabled(false); // 禁止调整分割线位置

        add(splitPane, BorderLayout.CENTER);
    }
    
    private String[] getMenuItemsForRole(User.UserRole role) {
        switch (role) {
            case ADMIN:
                return new String[]{"首页", "学生管理", "教师管理", "课程管理", "成绩管理", "退出系统"};
            case STUDENT:
                return new String[]{"首页", "我的课程", "选课中心", "我的成绩", "个人信息", "退出系统"};
            case TEACHER:
                return new String[]{"首页", "我的授课", "成绩录入", "个人信息", "退出系统"};
            default:
                return new String[]{"首页", "退出系统"};
        }
    }
    
    private void loadInitialPanel() {
        CardLayout cl = (CardLayout)(mainContentPanel.getLayout());
        
        // 添加首页面板
        HomePanel homePanel = new HomePanel(currentUser);
        mainContentPanel.add(homePanel, "首页");
        
        // 根据用户角色添加相应的面板
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            // 管理员面板
            StudentManagementPanel studentPanel = new StudentManagementPanel();
            mainContentPanel.add(studentPanel, "学生管理");
            
            TeacherManagementPanel teacherPanel = new TeacherManagementPanel();
            mainContentPanel.add(teacherPanel, "教师管理");
            
            CourseManagementPanel coursePanel = new CourseManagementPanel();
            mainContentPanel.add(coursePanel, "课程管理");
            
            GradeManagementPanel gradePanel = new GradeManagementPanel();
            mainContentPanel.add(gradePanel, "成绩管理");
        } else if (currentUser.getRole() == User.UserRole.STUDENT) {
            // 学生面板
            MyCoursePanel myCoursePanel = new MyCoursePanel(currentUser);
            mainContentPanel.add(myCoursePanel, "我的课程");
            
            CourseSelectionPanel courseSelectionPanel = new CourseSelectionPanel(currentUser);
            mainContentPanel.add(courseSelectionPanel, "选课中心");
            
            MyGradePanel myGradePanel = new MyGradePanel(currentUser);
            mainContentPanel.add(myGradePanel, "我的成绩");
            
            PersonalInfoPanel personalInfoPanel = new PersonalInfoPanel(currentUser);
            mainContentPanel.add(personalInfoPanel, "个人信息");
        } else if (currentUser.getRole() == User.UserRole.TEACHER) {
            // 教师面板
            // TODO: 实现教师相关面板
            PersonalInfoPanel personalInfoPanel = new PersonalInfoPanel(currentUser);
            mainContentPanel.add(personalInfoPanel, "个人信息");
        }
        
        // 添加退出系统功能
        JPanel exitPanel = new JPanel();
        exitPanel.setLayout(new BorderLayout());
        exitPanel.setBackground(new Color(245, 245, 250));
        
        // 创建带有图标的标题
        JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        headerPanel.setBackground(new Color(245, 245, 250));
        headerPanel.setBorder(BorderFactory.createEmptyBorder(40, 0, 20, 0));
        
        // 使用IconUtil获取退出图标
        JLabel iconLabel = new JLabel(com.studentmanagement.util.IconUtil.getExitIcon());
        headerPanel.add(iconLabel);
        
        JPanel messagePanel = new JPanel();
        messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS));
        messagePanel.setBackground(new Color(245, 245, 250));
        messagePanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 30, 20));
        
        JLabel titleLabel = new JLabel("退出系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(44, 62, 80));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        JLabel messageLabel = new JLabel("您确定要离开学生信息管理系统吗？");
        messageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        messageLabel.setForeground(new Color(127, 140, 141));
        messageLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        // 添加组件到消息面板
        messagePanel.add(titleLabel);
        messagePanel.add(Box.createRigidArea(new Dimension(0, 15)));
        messagePanel.add(messageLabel);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(new Color(245, 245, 250));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 40, 0));
        
        // 创建漂亮的按钮
        JButton logoutButton = new JButton("退出登录");
        logoutButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        logoutButton.putClientProperty("JButton.buttonType", "roundRect");
        logoutButton.setBackground(new Color(52, 152, 219));
        logoutButton.setForeground(Color.WHITE);
        logoutButton.setFocusPainted(false);
        
        JButton exitButton = new JButton("关闭系统");
        exitButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        exitButton.putClientProperty("JButton.buttonType", "roundRect");
        exitButton.setBackground(new Color(231, 76, 60));
        exitButton.setForeground(Color.WHITE);
        exitButton.setFocusPainted(false);
        
        JButton cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cancelButton.putClientProperty("JButton.buttonType", "roundRect");
        cancelButton.setBackground(new Color(236, 240, 241));
        cancelButton.setForeground(new Color(44, 62, 80));
        cancelButton.setFocusPainted(false);
        
        // 设置按钮大小
        Dimension buttonSize = new Dimension(120, 40);
        logoutButton.setPreferredSize(buttonSize);
        exitButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        
        // 设置按钮监听器
        logoutButton.addActionListener(e -> logout());
        exitButton.addActionListener(e -> exitSystem());
        cancelButton.addActionListener(e -> {
            // 返回首页
            menuList.setSelectedIndex(0);
            cl.show(mainContentPanel, "首页");
        });
        
        // 添加悬停效果
        logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                logoutButton.setBackground(new Color(41, 128, 185));
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                logoutButton.setBackground(new Color(52, 152, 219));
            }
        });
        
        exitButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                exitButton.setBackground(new Color(192, 57, 43));
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                exitButton.setBackground(new Color(231, 76, 60));
            }
        });
        
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                cancelButton.setBackground(new Color(224, 224, 224));
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                cancelButton.setBackground(new Color(236, 240, 241));
            }
        });
        
        // 水平排列按钮
        buttonPanel.add(logoutButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(15, 0)));
        buttonPanel.add(exitButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(15, 0)));
        buttonPanel.add(cancelButton);
        
        // 添加所有组件到退出面板
        exitPanel.add(headerPanel, BorderLayout.NORTH);
        exitPanel.add(messagePanel, BorderLayout.CENTER);
        exitPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        mainContentPanel.add(exitPanel, "退出系统");
        
        // 显示首页
        cl.show(mainContentPanel, "首页");
        
        // 设置菜单选择监听器
        menuList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                String selectedMenu = menuList.getSelectedValue();
                CardLayout cardLayout = (CardLayout) mainContentPanel.getLayout();
                cardLayout.show(mainContentPanel, selectedMenu);
            }
        });
    }
    
    // 退出登录
    private void logout() {
        int result = JOptionPane.showConfirmDialog(
                this,
                "确定要退出登录吗？",
                "退出登录",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE
        );
        
        if (result == JOptionPane.YES_OPTION) {
            dispose(); // 关闭当前窗口
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        }
    }
    
    // 关闭系统
    private void exitSystem() {
        int result = JOptionPane.showConfirmDialog(
                this,
                "确定要关闭系统吗？",
                "关闭系统",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE
        );
        
        if (result == JOptionPane.YES_OPTION) {
            System.exit(0); // 关闭应用程序
        }
    }
    
    // 辅助方法：根据名称查找组件
    private Component findComponentByName(Container container, String name) {
        for (Component component : container.getComponents()) {
            if (name.equals(component.getName())) {
                return component;
            }
        }
        return null;
    }
} 